package cn.haohaowo.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;

@Configuration
public class HibernateDBConfiguration {

	private Logger log = LoggerFactory.getLogger(MybatisDBConfiguration.class);
	
	@Autowired
	private CommonProperties commonProperties;
	
	@Bean(name="hibernateDataSource", destroyMethod="close")
	public DataSource getDataSource() {
		BasicDataSource basicDataSource = new BasicDataSource();
		basicDataSource.setDriverClassName(commonProperties.getJdbcDriver());
		basicDataSource.setUrl(commonProperties.getJdbcUrl());
		basicDataSource.setUsername(commonProperties.getJdbcUser());
		basicDataSource.setPassword(commonProperties.getJdbcPassword());
		
		return basicDataSource;
	}
	
	public SessionFactory getSqlSessionFactory(@Qualifier("") DataSource dataSource) throws Exception {
		AnnotationSessionFactoryBean annotationSessionFactoryBean = new AnnotationSessionFactoryBean();
//		annotationSessionFactoryBean.setNamingStrategy(org.hibernate.cfg.DefaultNamingStrategy.class);
		Properties properties = new Properties();
		properties.setProperty("hibernate.dialect", commonProperties.getJdbcDriver());
		annotationSessionFactoryBean.setHibernateProperties(properties);
		
		SessionFactory sqlSessionFactory = annotationSessionFactoryBean.getObject();
		return sqlSessionFactory;
	}
}
